/**
 * Created by ZHOUSH on 11/27/2015.
 */
var oracledb = require('oracledb');
var StringDecoder = require('string_decoder').StringDecoder;
var events = require('events');
var emitter = new events.EventEmitter();
var connstr = require('./connstr.js');
var sample = '(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = hkln687p.oocl.com)(PORT = 1521)) (CONNECT_DATA = (SERVER=DEDICATED) (SID = hllpqa)))';
var conn = connstr.use('LLP', 'PRD', 'SUPP');
var done = function (obj, err) {
    if (err) console.log(err);
    if (!obj) return;
    var errHandle = function (err) {
        if (err) {
            console.log(err);
        }
    };
    if (obj.release) {
        obj.release(errHandle);
        console.log('Released');
    }
    if (obj.close) {
        obj.close(errHandle);
        console.log('Closed');
    }
};
var directQuery = function (connStr, sql, final, progress, rownum) {
    var result = [];
    oracledb.getConnection(connStr, function (err, conn) {
            if (err) {
                done(null, err);
                final(err, result);
            }
            emitter.once('error', function (err) {
                final(err, void 0);
                done(conn, err);
            });
            emitter.once('end', function (data) {
                done(conn);
            });
            conn.execute(sql, [], {
                resultSet: true
            }, function (err, rs) {
                if (err) {
                    emitter.emit('error', err, void 0);
                } else {
                    result.metaData = rs.metaData;
                    fetchOneRowFromRS(conn, rs.resultSet, function (err, rows) {
                        if (err) {
                            emitter.emit('error', err, void 0);
                        } else if (!rows || rows.length == 0) {
                            final(void 0, result);
                        } else {
                            for (var i = 0; i < rows.length; i++) {
                                result.push(rows[i]);
                                if (progress) {
                                    progress(result.length);
                                }
                            }
                        }
                    }, rownum);
                }
            });
        }
    );
};
var fetchOneRowFromRS = function (conn, rs, callback, rn) {
    rn = rn || 50;
    rs.getRows(rn, function (err, rows) {
        if (err) {
            done(rs);
            callback(err, void 0);
        } else {
            if (rows && rows.length != 0) {
                callback(null, rows);
                fetchOneRowFromRS(conn, rs, callback, rn);
            } else {
                done(rs);
                callback(null, rows);
            }
        }
    });
};
var directCount = function (conn, sql, callback) {
    directQuery(conn, 'SELECT COUNT(1) FROM (' + sql + ')', function (err, rs) {
        if (err) {
            callback(err, void 0);
        } else {
            callback(void 0, rs[0][0]);
        }
    });
};
var progressQuery = function (conn, sql, callback, progress, rownum) {
    directCount(conn, sql, function (err, len) {
        if (err) {
            console.log(err);
        } else {
            directQuery(conn, sql, callback, function (curr) {
                progress(curr, len)
            }, rownum);
        }
    })
};

directQuery(conn,
    'select sql_str from HLLP_OBJ_ADMIN.llp_rpt_oracle_jxls where ora_rpt_rdf_name = \'RPT_ICS_INVOICE_GY\' and sheet_no = 2',
    function (err, rs) {
        if (err) console.log(err);
        else {
            var blob = asObject(rs)[0]['SQL_STR'];//[0]['SQL_STR'];
            blob.setEncoding('utf8');
            blob.on('data', function (data) {
                console.log(data);
            }).on('close', function () {
                emitter.emit('end');
            });
            //console.log(blob);
        }
        //else console.log(rs);
    });

var asObject = function (rs) {
    return rs.map(function (item) {
        var obj = {};
        rs.metaData.forEach(function (col, idx) {
            obj[col.name] = item[idx];
        });
        return obj;
    })
};
var asSQL = function (sql) {
    var _in = false, seg = [], one = '';
    for (var i = 0; i < sql.length; i++) {
        if (sql[i] == "'") {
            _in = !_in
        }
        if (sql[i] == ';') {
            if (!_in) {
                if (one) {
                    seg.push(one);
                    one = '';
                }
            }
            continue;
        }
        one += sql[i];
    }
};


exports.directQuery = directQuery;
exports.directCount = directCount;
exports.progressQuery = progressQuery;
exports.asObject = asObject;